#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
from common import *
import config

filestocleanup = []

def cleanup():
    while filestocleanup:
        removeFile(filestocleanup.pop())

def encodeAudio(fname, output, options):
    audioCodec = options['audiocodec']
    audioCodecOptions = options['audiocodecoptions']
    if audioCodec in ['aac', 'ac3']:
        execute('%s -i "%s" -y %s "%s"' % (config.toolPaths['avconv'], fname, audioCodecOptions, output))
    elif audioCodec == 'mp3':
        execute('%s %s "%s" "%s"' % (config.toolPaths['lame'], audioCodecOptions, fname, output))
    filestocleanup.append(output)

def encodeVideo(fname, output, options):
    passes = int(options['passes'])
    passlogFileName = os.path.splitext(fname)[0] + "passlog.log"
    for i in range(passes):
        currentPass = i + 1
        videoCodec = options['videocodec']
        filteroptions = options['videofilteroptions']
        videoCodecOptions = options['videocodecoptionspass%d'%(currentPass)]
        if currentPass < passes:
            outputfile = os.path.devnull
        else:
            outputfile = output
        execute('%s "%s" -o "%s" -passlogfile "%s" -vf %s -ovc %s -%s:pass=%d'
            % (config.toolPaths['mencoder'], fname, outputfile, passlogFileName, filteroptions, videoCodec, videoCodecOptions, currentPass))
    if output != "/dev/null":
        filestocleanup.append(output)
    filestocleanup.append(passlogFileName)
    filestocleanup.append(passlogFileName + '.mbtree')
